<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getlist">
            <el-button slot="append" icon="el-icon-search" @click="getlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addVisible =true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userslist" border style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="手机号" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scoped">
            <el-switch v-model="scoped.row.mg_state" @change="changeState(scoped.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="edituser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="deleteuser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="修改角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="small"
                icon="el-icon-setting"
                @click="editrole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog title="添加用户" :visible.sync="addVisible" width="60%" @close="addresets">
      <el-form :model="addForm" :rules="addrules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tell">
          <el-input v-model="addForm.tell"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="modifyVisible" width="60%" @close="modifyresets">
      <el-form :model="modifyForm" :rules="modifyrules" ref="modifyFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="modifyForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="modifyForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyTrue">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改角色" :visible.sync="modifyRoleVisible" width="60%" @close="modifyRoleresets">
      <el-row :gutter="20">
        <el-col :span="4">
          <span>用户名:</span>
        </el-col>
        <el-col :span="20">{{roleinfo.username}}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <span>角色名称:</span>
        </el-col>
        <el-col :span="20">{{roleinfo.role_name}}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <span>新角色名称:</span>
        </el-col>
        <el-col :span="20">
          <el-select v-model="xinrole" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyRoleTrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };

    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };

    return {
      addVisible: false,
      modifyVisible: false,
      modifyRoleVisible: false,
      userslist: [],
      roleinfo: {},
      rolelist:[],
      xinrole:"",
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      total: null,
      addForm: {
        username: "",
        password: "",
        email: "",
        tell: ""
      },
      modifyForm: {},
      addrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        tell: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" }
        ]
      },
      modifyrules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    handleSizeChange(index) {
      this.queryinfo.pagesize = index;
      this.getlist();
    },
    handleCurrentChange(index) {
      this.queryinfo.pagenum = index;
      this.getlist();
    },
    getlist() {
      this.$http.get("users", { params: this.queryinfo }).then(res => {
        //console.log(res)
        this.userslist = res.data.data.users;
        this.total = res.data.data.total;
        //console.log(res.data.data.total);
      });
    },
    addresets() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(validate => {
        if (validate) {
          this.$http.post("users", this.addForm).then(res => {
            //console.log(res);
            if (res.data.meta.status != 201) {
              this.$message.error(res.data.meta.msg);
            } else {
              this.$message.success(res.data.meta.msg);
              this.addVisible = false;
              this.getlist();
            }
          });
        } else {
          this.$message.error("格式错误");
        }
      });
    },
    changeState(obj) {
      //console.log(obj);
      this.$http.put("users/" + obj.id + "/state/" + obj.mg_state).then(res => {
        console.log(res);
        if ((res.data.meta.status = !200)) {
          this.$message.error(res.data.meta.msg);
          obj.mg_state = !obj.mg_state;
        } else {
          this.$message.success(res.data.meta.msg);
        }
      });
    },
    edituser(id) {
      //console.log(id);
      this.modifyVisible = true;
      this.$http.get("users/" + id).then(res => {
        this.modifyForm = res.data.data;
      });
    },
    modifyTrue() {
      this.$refs.modifyFormRef.validate(validate => {
        if (!validate) {
          return;
        }
        this.$http
          .put("users/" + this.modifyForm.id, {
            email: this.modifyForm.email,
            mobile: this.modifyForm.mobile
          })
          .then(res => {
            this.$message.success("用户修改成功");
            this.getlist();
            this.modifyVisible = false;
          });
      });
    },
    modifyresets() {
      this.$refs.modifyFormRef.resetFields();
    },
    deleteuser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete("users/" + id).then(res => {
            // console.log(res.data.meta.status);

            if (res.data.meta.status !== 200) {
              return this.$message({
                type: "error",
                message: "删除失败"
              });
            }
            this.getlist();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    editrole(roleinfo) {
      this.roleinfo = roleinfo;
      console.log(this.roleinfo);
      this.$http.get('roles').then(res => {
        this.rolelist = res.data.data;
        //console.log(this.rolelist)
      })
      this.modifyRoleVisible = true;
    },
    modifyRoleresets() {
      this.xinrole="";
    },
    modifyRoleTrue() {
      if(!this.xinrole) {
        return this.$message.success("请输入新角色");

      }
      this.$http.put(`users/${this.roleinfo.id}/role`,{rid:this.xinrole}).then(res => {
        //console.log(res.data.meta.status)
        if(res.data.meta.status !== 200){
          return this.$message.error(res.data.meta.msg);
        }
        this.getlist();
        this.modifyRoleVisible = false;        
        this.$message.success("分配角色成功");

      })
    }
  },
  mounted() {
    this.getlist();
  }
};
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.el-row {
  margin-bottom: 10px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
